package com.starmark.gateway.springcloud.provider.proxy.web;

import com.alibaba.fastjson.JSON;
import com.starmark.gateway.springcloud.provider.constants.GatewayConstant;
import com.starmark.gateway.springcloud.provider.dto.PtInterfaceDto;
import com.starmark.gateway.springcloud.provider.response.Response;
import com.starmark.gateway.springcloud.provider.service.ICacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;

import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;


/**
 * 网关接口测试
 *
 * @author starmark
 * @since 2020/8/15 001510:37
 **/
@Controller
@RequestMapping()
public class GatewayInterfaceController {


    @Autowired
    private ICacheService cacheService;



    @RequestMapping("/{projectCode}/{interfaceCode}/interfaceInvoke")
    @ResponseBody
    public Response interfaceInvoke(@PathVariable("projectCode") String projectCode, @PathVariable("interfaceCode") String interfaceCode,
                                     ServerWebExchange exchange
    ) {


        System.out.println(""+exchange.getAttribute( "cachedRequestBody"));

        java.lang.String bodyStr =exchange.getAttribute( "cachedRequestBodyStr");
        System.out.println(bodyStr);
        //获取相关的配置
        String interfaceInfo = cacheService.getCacheByKey(GatewayConstant.STARMARK_GATEWAY_INTERFACES + projectCode + ":" + interfaceCode);
        PtInterfaceDto interfaceDto = JSON.parseObject(Objects.requireNonNull(JSON.parse(interfaceInfo)).toString(), PtInterfaceDto.class);
        Assert.notNull(interfaceDto, "接口配置不存在");
        Assert.isTrue(interfaceDto.getStatus(), "接口已下架，请勿调用");

        return null;
    }


    private String  getBodyContent(ServerWebExchange exchange){
        Flux<DataBuffer> body= exchange.getRequest().getBody();


        AtomicReference<String> bodyString = new AtomicReference<>();
        body.publish().subscribe(buffer -> {
            byte[] bytes = new byte[buffer.readableByteCount()];
            buffer.read(bytes);
            DataBufferUtils.release(buffer);
            bodyString.set(new String(bytes, StandardCharsets.UTF_8));
        });

        return bodyString.get();

    }


}
